const querystring = require('querystring');
const { getPostData, getCookie } = require('./src/common/utils');
// const { getRedis, setRedis } = require('./src/db/redis');
const { access } = require('./src/common/log');
const handleBlogRouter = require('./src/router/blog');
const handleUserRouter = require('./src/router/user');


const serverHandler = (req, res) => {
    const url = req.url;
    const path = url.split('?')[0];
    const queryString = url.split('?')[1];

    req.path = path || '/';
    req.queryString = queryString || '';
    req.query = querystring.parse(queryString);
    req.cookie = getCookie(req);

    // 记录 access log
    access(`${req.method} -- ${req.url} -- ${req.headers['user-agent']} -- ${new Date().toLocaleString()}`);

    res.setHeader('content-type', 'application/json');

    // 先处理 postData
    getPostData(req).then(postData => {
        req.body = postData;

        const blogResult = handleBlogRouter(req, res);
        const userResult = handleUserRouter(req, res);

        if (blogResult) {
            blogResult.then(blogData => {
                res.end(JSON.stringify(blogData));
            });
            return ;
        }

        if (userResult) {
            userResult.then(userData => {
                res.end(JSON.stringify(userData));
            });
            return ;
        }

        res.writeHead(404, { 'Content-type': 'text/plain' });
        res.write('404 Not Found');
        res.end();
    });
};

module.exports = serverHandler;
